package Lok;

import java.util.concurrent.locks.ReentrantLock;

//  测试Lok锁
public class LokTest implements Runnable {

    private int piao = 20;
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true) {
            try {
                lock.lock();
                if (piao > 0) {
                    System.out.println(Thread.currentThread().getName() + "拿到了第" + piao-- + "票");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    break;
                }
            } finally {
                lock.unlock();
                System.out.println("把锁关了");
            }
        }
    }

    public static void main(String[] args) {
        LokTest lokTest = new LokTest();
         new Thread(lokTest, "1111").start();
        new Thread(lokTest, "2222").start();
        new Thread(lokTest, "33333").start();
        new Thread(lokTest, "44444").start();
    }
}
